package com.stylefeng.guns.modular.payroll.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.aop.Platform;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.payroll.service.IPayrollService;
import com.stylefeng.guns.modular.system.model.Payroll;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工工资控制器
 *
 * @author fengshuonan
 * @Date 2018-07-09 13:52:05
 */
@Controller
@RequestMapping("/payroll")
public class PayrollController extends BaseController {

    private String PREFIX = "/payroll/payroll/";

    @Autowired
    private IPayrollService payrollService;

    /**
     * 跳转到员工工资首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "payroll.html";
    }


    /**
     * 跳转到添加员工工资
     */
    @RequestMapping("/payroll_add")
    public String payrollAdd() {
        return PREFIX + "payroll_add.html";
    }

    /**
     * 跳转到添加员工工资
     */
    @RequestMapping("/payroll_upload")
    public String payrollUpload() {
        return PREFIX + "payroll_upload.html";
    }


    /**
     * 跳转到修改员工工资
     */
    @RequestMapping("/payroll_update/{payrollId}")
    public String payrollUpdate(@PathVariable Integer payrollId, Model model) {
        Payroll payroll = payrollService.selectById(payrollId);
        model.addAttribute("item",payroll);
        LogObjectHolder.me().set(payroll);
        return PREFIX + "payroll_edit.html";
    }

    /**
     * 获取员工工资列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String payTime, @Platform String platform) throws Exception{
        if (!StringUtils.isNotEmpty(payTime)){
            payTime = DateUtil.format(new Date(),"yyyy-MM");
        }
        Page<Payroll> page = new PageFactory<Payroll>().defaultPage();
        EntityWrapper<Payroll> wrapper = new EntityWrapper<Payroll>();
        wrapper.eq("platform",platform);
        wrapper.eq("pay_time",payTime);
        wrapper.orderBy("pay_time",false);
        Page<Payroll> payrollPage = payrollService.selectPage(page,wrapper);
        //填充字典类型
        payrollPage.setRecords((List<Payroll>)new BaseModelWarpper(payrollPage.getRecords(),Payroll.class).warpToObj());
        return super.packForBT(payrollPage);
    }

    /**
     * 新增员工工资
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @BussinessLog(value = "新增员工工资")
    public Object add(Payroll payroll) {
        if (payroll.getPayTime()==null) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "工资月份不能为空");
        }
        //组装查询
        EntityWrapper<Payroll> wrapper = new EntityWrapper<Payroll>();
        wrapper.eq("platform",ShiroKit.getUser().getDeptcode());
        wrapper.eq("paytime",payroll.getPayTime());
        wrapper.eq("username",payroll.getUsername());
        wrapper.eq("usercode",payroll.getUsercode());
        //检查是否已经存在
        if(payrollService.selectCount(wrapper)>0){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,payroll.getUsername()+"--"+payroll.getPayTime()+"数据已存在");
        }
        payroll.setPlatform(ShiroKit.getUser().getDeptcode());
        payroll.setCreattime(new Date());
        payrollService.insert(payroll);
        return SUCCESS_TIP;
    }

    /**
     * 删除员工工资
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除员工工资")
    public Object delete(@RequestParam Integer payrollId) {
        payrollService.deleteById(payrollId);
        return SUCCESS_TIP;
    }

    /**
     * 修改员工工资
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改员工工资")
    public Object update(Payroll payroll) {
        payroll.setPlatform(ShiroKit.getUser().getDeptcode());
        payroll.setUpdatetime(new Date());
        payrollService.updateById(payroll);
        return SUCCESS_TIP;
    }

    /**
     * 描述:文件导入
     * 创建人: yu
     * 日期: 2018/7/27
     * 时间: 17:01
     */
    @PostMapping( "/upload")
    @ResponseBody
    @BussinessLog(value = "导入员工工资")
    public Object upload(@RequestParam("file") MultipartFile file,
                                          HttpServletRequest request)throws GunsException,Exception{
        payrollService.adds(file);
        return SUCCESS_TIP;


    }

    /**
     * 员工工资详情
     */
    @RequestMapping(value = "/detail/{payrollId}")
    @ResponseBody
    public Object detail(@PathVariable("payrollId") Integer payrollId) {
        return payrollService.selectById(payrollId);
    }


   /**
    * 描述:到出工资
    * 创建人: xiang
    * 日期: 2018/7/27
    * 时间: 17:00
    */
    @RequestMapping("/load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response,String payTime)  {


            //查询要导出工资
            if (StringUtils.isBlank(payTime)){
                throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请选择要导出的工资表时间");
            }

           String platform = ShiroKit.getUser().getDeptcode();//获取当前平台
            //组装插叙数据
            EntityWrapper<Payroll> wrapper  = new EntityWrapper<>();
            wrapper.eq("platform",platform);
            wrapper.eq("pay_time",payTime);

            //查询要导出的工资表数据
            List<Payroll> payrollList = payrollService.selectList(wrapper);

            //初始化导出的模板表格
            TemplateExportParams params = new TemplateExportParams(
                    "exceldoc/payroll.xlsx");
            Map<String, Object> map = new HashMap<String, Object>();
            //组装下载数据
            map.put("maplist", payrollService.load(payrollList));
            map.put("name",platform+payTime.replace("-","年")+"月工资表");

            modelMap.put(TemplateExcelConstants.FILE_NAME, platform+payTime+"工资表");
            modelMap.put(TemplateExcelConstants.PARAMS, params);
            modelMap.put(TemplateExcelConstants.MAP_DATA, map);
            PoiBaseView.render(modelMap, request, response,
                    TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }

    /**
     * 描述:到出工资表模板
     * 创建人: xiang
     * 日期: 2018/7/27
     * 时间: 17:00
     */
    @RequestMapping("/download")
    public void download(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response)  {

        String platform = ShiroKit.getUser().getDeptcode();//获取当前平台
        String time = new SimpleDateFormat("yyyy-mm").format(new Date());

        //初始化导出的模板表格
        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/payrollModel.xlsx");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name",platform.toUpperCase()+time.replace("-","年")+"月工资表");

        modelMap.put(TemplateExcelConstants.FILE_NAME, platform.toUpperCase()+time.replace("-","年")+"月工资表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }
}
